//
//  UIImage+ext.swift
//  EPHome
//
//  Created by liujianlong on 2022/8/1.
//

import UIKit
let tableName = "webImageDB"
@objc public extension UIImage
{
    class func withURL(_ url:String, _ block:((_ img:UIImage)->Void)?=nil)->URLSessionTask?
    {
//        if url.count <= 0{return URLSessionTask()}
//        
//        let ccdb = CCDB();
//        ccdb.openDM(tableName)
//        ccdb.createTable(tableName, withOptions: ["url","data"])
//        
//        
//        let array = ccdb.select(tableName, withOptions: ["data"], conditionsDict: ["url":url])
//        if array.count > 0{
//            let data = (array.firstObject as! NSDictionary).value(forKey:"data")
//            let img = UIImage(data:data as! Data)
//            block?(img!)
//            return URLSessionTask.init()
//        }else{
//            return CCHttp.get(url, para: nil, header: nil) { response in
//                let img = response as? UIImage
//                let newImg = img?.tranToSize(CGSize(width:500, height:500))
//                let data = newImg?.jpegData(compressionQuality: 0.1)
//                block?(newImg!)
//                ccdb.insert(tableName, withDict: ["data":data,"url":url])
//            } fail: { error in}
//        }
        return nil
    }
    
    class func withColor(_ color:UIColor)->UIImage
    {
        let rect = CGRect(x:0, y:0, width:10.0, height: 10.0)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()
        context?.setFillColor(color.cgColor)
        context?.fill(rect)
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return img!
    }
    
    func base64()->String
    {
        let data = self.jpegData(compressionQuality:1.0)
        return data!.base64EncodedString(options:.endLineWithCarriageReturn)
    }
}


@objc public extension UIImage{
    func tranToSize(_ size:CGSize)->UIImage{
        UIGraphicsBeginImageContext(size)
        self.draw(in: CGRect(x:0, y:0, width:size.width, height:size.height))
        let newimg = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newimg!
    }
}
